package com.youtills.core.config;

import com.youtills.core.io.IoInputStream;
import com.youtills.core.io.IoUtil;

import java.io.IOException;
import java.util.Properties;
import java.util.Set;

/**
 * Created by IntelliJ IDEA.
 * User: ravi
 * Date: 9/5/12
 * Time: 7:17 PM
 * To change this template use File | Settings | File Templates.
 */
class PropertyFileProvider implements IConfigProvider{

    private final Properties properties;
    private static final String FILE_EXTENSION = ".properties";

    PropertyFileProvider() {
        properties = new Properties();
    }

    public void init(String environment) {
        loadProperties(environment + FILE_EXTENSION, false);
    }

    private synchronized void loadProperties(String fileName, boolean reload){
        IoInputStream stream = IoUtil.getIoStream(fileName);
        if(stream != null && stream.getInputStream() != null){
            Properties props = new Properties();
            try {
                props.load(stream.getInputStream());
                // TODO - reload logic.
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }

            properties.putAll(props);
        }
    }

    public void refresh() {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public void addProperties(String source) {
        loadProperties(source, false);
    }

    public void addSource(String source, boolean reload) {
        loadProperties(source, reload);
    }

    public IConfigValue getConfigValue(String key) {

        String value = properties.getProperty(key);
        if(value != null){
            return new ConfigValue(value, "PropertyFileProvider");
        }
        return  null;
    }

    public Set<String> getConfigNames() {
        return properties.stringPropertyNames();
    }
}
